import { $http } from "@/http"
import {unref} from 'vue'
export function useRequest(options){
    let requestContext = null;
    const {
        method="GET",
        url="",
        params={},
        data={},
        config={},
        interceptingSuccessResult,
        interceptingErrorResult
    } = options;
    let slotProps = null;
    function register(requestAction){
        requestContext = requestAction;
        slotProps && setSlotProps(slotProps)
    }
    function setSlotProps(props){
        if(requestContext){
            slotProps = requestContext.slotProps.value = {
                ...requestContext.slotProps.value,
                ...props,
            }        
        }else{
            slotProps = props;
        }
    }
    function load(newConfig){
        setSlotProps({loading:true});
        return $http({
            method,
            url,
            params,
            data,
            isLoading:false,
            isError:false,
            ...config,
            ...newConfig,
        }).then((res) => {
            return setSlotProps({
                loading:false,
                data:interceptingSuccessResult ? interceptingSuccessResult(res) || res : res
            });
        }).catch((err) => {
            let errorData  = interceptingErrorResult && interceptingErrorResult(err);
            if(errorData) setSlotProps({data: errorData,});
            return setSlotProps({
                loading:false,
            });
        }) 
    }
    return {
        register,
        requestContext,
        setSlotProps,
        load
    }
}